﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using Natural.Attributes;
using Natural.Model;

namespace Natural.Providers
{
    [Impl(Type = ImplType.Provider,Name="Logger", Strategy = "Default", Priority = 0, Version = 0)]
    public class EventLogger : ILogger
    {
        public void Log(Exception exception)
        {
            Log(Server.Context.SolutionName, exception.Message, EventLogEntryType.Error, exception.StackTrace);
        }
        public void Log(ActionContext context)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("request", Serializer.Serialize(context.Request));
            dic.Add("response", Serializer.Serialize(context.Response));
            Log(Server.Context.SolutionName, "Action", EventLogEntryType.Information, Serializer.Serialize(dic));
        }
        public void Log(InvokeContext context)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("request", Serializer.Serialize(context.Request));
            dic.Add("response", Serializer.Serialize(context.Response));
            Log(Server.Context.SolutionName, "Invoke", EventLogEntryType.Information, Serializer.Serialize(dic));
        }
        public void Log(string logName, string message)
        {
            Log(Server.Context.SolutionName, logName, EventLogEntryType.Information, message);
        }
        public void Log(string logName, EventLogEntryType type, string message)
        {
            Log(Server.Context.SolutionName, logName, type, message);
        }
        private void Log(string source,string logName,EventLogEntryType type,string message)
        {
            if (!EventLog.SourceExists(source))
            {
                EventLog.CreateEventSource(source, logName);
            }
            // Create an EventLog instance and assign its source.
            EventLog myLog = new EventLog();
            myLog.Source = source;
            // Write an informational entry to the event log.    
            myLog.WriteEntry(message, type);
        }
    }
}
